package com.linkhub.oms.admin.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

import static com.linkhub.oms.common.constant.ProjectConstant.ASYNC_EXECUTOR;

/**
 * @Description: AsyncConfig
 * @Author: echo
 * @Date: 2024/3/2 21:29
 * @Version: 1.0
 */
@Slf4j
@Configuration
public class AsyncConfig implements AsyncConfigurer {



    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    @Bean(ASYNC_EXECUTOR)
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(10000);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("task-async-");
        executor.setRejectedExecutionHandler((r, exe) -> {
            throw new RejectedExecutionException("taskExecutor async thread pool is full,throw RejectedExecutionException:" + r.toString() +
                    "; rejected from: " + exe.toString());
        });
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);
    }

    @Override
    public Executor getAsyncExecutor() {
        return taskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SpringAsyncExceptionHandler();
    }

    static class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.error("taskExecutor handleUncaughtException() - exception=[{}], method=[{}], params=[{}]",
                    Throwables.getStackTraceAsString(throwable), method.getDeclaringClass() + "#" + method.getName(),
                    StringUtils.join(objects, ", "), throwable);
        }
    }

}
